import Foundation

@MainActor
class LoginViewModel: ObservableObject {
    @Published var phoneNumber = ""
    @Published var isAgreedToTerms = false
    @Published var isLoading = false
    @Published var errorMessage: String? = nil
    @Published var isLoginSuccessful = false
    
    private let loginUseCase: LoginUseCase
    
    init(loginUseCase: LoginUseCase) {
        self.loginUseCase = loginUseCase
    }
    
    var isPhoneNumberValid: Bool {
        let phoneRegex = "^1[3-9]\\d{9}$"
        let idCardRegex = "^[1-9]\\d{5}(19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\\d|3[01])\\d{3}[0-9Xx]$"
        
        let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneRegex)
        let idCardTest = NSPredicate(format: "SELF MATCHES %@", idCardRegex)
        
        return phoneTest.evaluate(with: phoneNumber) || idCardTest.evaluate(with: phoneNumber)
    }
    
    func login() async {
        isLoading = true
        errorMessage = nil
        
        do {
            let user = try await loginUseCase.login(phoneNumber: phoneNumber, isAgreedToTerms: isAgreedToTerms)
            DispatchQueue.main.async {
                self.isLoginSuccessful = true
            }
            print("Login successful: \(user)")
        } catch {
            errorMessage = error.localizedDescription
        }
        
        isLoading = false
    }
}
